<template>
  <div class="filter-life-cycle consumption-container">
    <px-form ref="formRef" :model="queryParams" :inline="true" class="custom-form-ui">
      <px-form-item style="display: none" label="厂区">
        <px-select
          v-model="queryParams.factory"
          placeholder="请选择厂区"
          clearable
          @change="
            getSystemOptions;
            getEquipOptions;
            getMaterialOptions;
          "
        >
          <px-option v-for="item in factoryOptions" :key="item.itemValue" :label="item.name" :value="item.itemValue" />
        </px-select>
      </px-form-item>
      <px-form-item label="科室">
        <px-select
          v-model="queryParams.className"
          disabled
          placeholder="请选择科室"
          @change="
            getSystemOptions;
            getEquipOptions;
            getMaterialOptions;
          "
        >
          <px-option v-for="item in depOptions" :key="item.itemValue" :label="item.name" :value="item.itemValue" />
        </px-select>
      </px-form-item>
      <px-form-item style="width: 350px !important" label="系统">
        <px-tree-select
          v-model="queryParams.systemName"
          clearable
          style="width: 100%"
          placeholder="请选择设备系统（树状图）"
          :props="defaultProps"
          filterable
          :data="systemList"
          check-strictly="true"
          :render-after-expand="false"
          collapse-tags
          collapse-tags-tooltip
          @change="treeChage"
        />
      </px-form-item>
      <px-form-item style="width: 350px !important" label="设备">
        <px-select
          v-model="queryParams.eqpId"
          style="width: 100%"
          filterable
          remote
          reserve-keyword
          remote-show-suffix
          clearable
          :remote-method="remoteMethod"
          placeholder="请选择设备"
        >
          <px-option v-for="(item, index) in equipOptions" :key="index" :label="item" :value="item" />
        </px-select>
      </px-form-item>
      <px-form-item style="width: 350px !important" label="耗材名称">
        <px-select v-model="queryParams.type" style="width: 100%" filterable placeholder="请选择耗材名称" clearable>
          <px-option v-for="(item, index) in materialOptions" :key="index" :label="item" :value="item" />
        </px-select>
      </px-form-item>
      <px-form-item label="使用时间" style="width: 450px !important">
        <px-date-picker
          v-model="dateRange"
          type="datetimerange"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
          :default-time="defaultTime"
        />
      </px-form-item>
      <px-button style="margin-top: -17px" type="primary" @click="handleQuery">查询</px-button>
      <px-button style="margin-top: -17px" @click="resetQuery">重置</px-button>
    </px-form>
    <div ref="objectModelTableRef" v-loading="tableLoading" class="table-content">
      <px-table :data="tableData" size="small" border class="common-table" :header-cell-style="headerCellStyleFn" height="calc(100vh - 349px)">
        <px-table-column label="序号" width="60" align="center" fixed="left">
          <template #default="{ $index }">
            {{ (queryParams.pageNum - 1) * queryParams.pageSize + $index + 1 }}
          </template>
        </px-table-column>
        <px-table-column prop="ffuId" label="所属设备" show-overflow-tooltip />
        <px-table-column prop="filterType" label="耗材名称" min-width="100">
          <template #default="scope">
            <div
              v-for="(item, index) in getFilterTypes(scope.row.filters)"
              :key="index"
              class="filter_bro flex flex-col justify-center"
              :style="{ minHeight: `${24 * getFilterItemLen(Object.values(scope.row.filters)[index])}px` }"
            >
              {{ item }}
            </div>
          </template>
        </px-table-column>
        <px-table-column prop="filterCode" label="备件编码" min-width="150">
          <template #default="scope">
            <div v-for="(filters, index) in Object.values(scope.row.filters) as any[]" :key="index" class="filter_bro">
              <div v-for="(filter, index) in filters as any[]" :key="index" class="filter_bro">
                <div v-for="(detail, index) in filter.detailMap as any[]" :key="index" class="filter_bro">
                  {{ detail.detailCode }}
                </div>
              </div>
            </div>
          </template>
        </px-table-column>

        <!-- <px-table-column prop="detailName" label="系统" fixed min-width="120" show-overflow-tooltip /> -->
        <px-table-column prop="filterSpc" label="规格型号" min-width="120">
          <template #default="scope">
            <div v-for="(filters, index) in Object.values(scope.row.filters) as any[]" :key="index" class="filter_bro">
              <div v-for="(filter, index) in filters as any[]" :key="index" class="filter_bro">
                <div v-for="(detail, index) in filter.detailMap as any[]" :key="index" class="filter_bro">
                  {{ detail.detailName }}
                </div>
              </div>
            </div>
          </template>
        </px-table-column>
        <px-table-column prop="filterMaker" label="品牌" min-width="60">
          <template #default="scope">
            {{ getSingleItem(scope.row.filters, "filterMaker") }}
            <!-- {{ Object.values(scope.row.filters)[0][0]["filterMaker"] }} -->
          </template>
        </px-table-column>
        <!-- <px-table-column prop="filterInstallDate" label="单位"  min-width="120" show-overflow-tooltip /> -->
        <px-table-column prop="filterNumber" label="数量" min-width="60" show-overflow-tooltip>
          <template #default="scope">
            <div v-for="(filters, index) in Object.values(scope.row.filters) as any[]" :key="index" class="filter_bro">
              <div v-for="(filter, index) in filters as any[]" :key="index" class="filter_bro">
                <div v-for="(detail, index) in filter.detailMap as any[]" :key="index" class="filter_bro">
                  {{ detail.detailNum }}
                </div>
              </div>
            </div>
          </template>
        </px-table-column>
        <!-- <px-table-column prop="lifecycle_predict" label="出库单号"  min-width="60" show-overflow-tooltip /> -->
        <px-table-column prop="startTime" label="开始使用时间" min-width="120" show-overflow-tooltip>
          <template #default="scope">
            <div v-for="(filters, index) in Object.values(scope.row.filters)" :key="index" class="filter_bro">
              <div
                v-for="(filter, _index) in filters"
                :key="_index"
                class="filter_bro flex flex-col justify-center"
                :style="{ minHeight: `${24 * getFilterItemLen(Object.values(scope.row.filters)[index])}px` }"
              >
                {{ filter.startTime?.split(" ")[0] }}
              </div>
            </div>
          </template>
        </px-table-column>
        <px-table-column prop="endTime" label="结束使用时间" min-width="100" show-overflow-tooltip>
          <template #default="scope">
            <span style="color: #3b82f6; cursor: pointer" @click="goPms(getSingleItem(scope.row.filters, 'filterOrderNo'))">
              {{ getSingleItem(scope.row.filters, "endTime")?.split(" ")[0] }}
            </span>
          </template>
        </px-table-column>
        <px-table-column prop="usedDay" label="实际使用时长" min-width="80">
          <template #default="scope">
            <!-- {{ getSingleItem(scope.row.filters, "usedDay") }} -->
            <div v-for="(filters, index) in Object.values(scope.row.filters)" :key="index" class="filter_bro">
              <div
                v-for="(filter, _index) in filters"
                :key="_index"
                class="filter_bro flex flex-col justify-center"
                :style="{ minHeight: `${24 * getFilterItemLen(Object.values(scope.row.filters)[index])}px` }"
              >
                {{ filter.usedDay }}
              </div>
            </div>
          </template>
        </px-table-column>
        <px-table-column prop="lifecycleExp" label="额定使用时长" min-width="80">
          <template #default="scope">
            <!-- {{ getSingleItem(scope.row.filters, "lifecycleExp") }} -->
            <div v-for="(filters, index) in Object.values(scope.row.filters)" :key="index" class="filter_bro">
              <div
                v-for="(filter, _index) in filters"
                :key="_index"
                class="filter_bro flex flex-col justify-center"
                :style="{ minHeight: `${24 * getFilterItemLen(Object.values(scope.row.filters)[index])}px` }"
              >
                {{ filter.lifecycleExp }}
              </div>
            </div>
          </template>
        </px-table-column>
        <px-table-column prop="lifecycleAct" label="预测使用时长" min-width="80">
          <template #default="scope">
            <!-- {{ getSingleItem(scope.row.filters, "lifecycleAct") }} -->
            <div v-for="(filters, index) in Object.values(scope.row.filters)" :key="index" class="filter_bro">
              <div
                v-for="(filter, _index) in filters"
                :key="_index"
                class="filter_bro flex flex-col justify-center"
                :style="{ minHeight: `${24 * getFilterItemLen(Object.values(scope.row.filters)[index])}px` }"
              >
                {{ filter.lifecycleAct }}
              </div>
            </div>
          </template>
        </px-table-column>
      </px-table>
      <pagination
        v-show="total > 0"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        class="equip-pagination"
        :total="total"
        @pagination="handleQuery"
      />
    </div>
  </div>
</template>
<script setup lang="ts">
defineOptions({
  name: "MACHINE_CONSUMABLEITEMSLIFECYCLE_FILTER_BAG_RECORD"
});
import { PxMessage } from "px-ui";
import { ref, reactive, onMounted, onUnmounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import {
  queryListByTypeCode,
  querySystemModelCondition,
  queryFilterListPage,
  listInstalledFiltersMachine,
  consumablelistInstalledDevices,
  getListHistoryGrouping
} from "@/api/modules/operation";
import { useRouterStoreHook } from "@/store/modules/router";
import { useUpdateDomHeight, useCancelUpdateDomHeight } from "@/hooks/useCommon";
import { querySystemSelect } from "@/api/equip/archive";
import { getToken } from "@/utils/auth";
const defaultProps = {
  children: "children",
  label: "name",
  value: "code"
};

const router = useRouter();
const route = useRoute();
const routerStore = useRouterStoreHook();
const factoryOptions = ref([]);
const total = ref(0);
const gap = 40;
const defaultHeight = 606;
const scrollbarHeight = ref<number>(defaultHeight);
const objectModelTableRef = ref<HTMLElement | null>(null);
const systemList = ref([]);

const defaultTime: [Date, Date] = [new Date(2000, 1, 1, 0, 0, 1), new Date(2000, 1, 1, 23, 59, 59)];
const dateRange = ref([]);

const handleSystemFocus = async () => {
  querySystemSelect({ factoryArea: "", className: queryParams.className }).then(res => {
    console.log(res[0].children[0].children);
    systemList.value = res[0].children;
  });
};
//获取厂区
const getFactoryOption = async () => {
  const params = { typeCode: "factoryArea" };
  factoryOptions.value = await queryListByTypeCode(params);
};
const depOptions = ref([]);
//获取科室
const getDepOption = async () => {
  const params = { typeCode: "className" };
  depOptions.value = await queryListByTypeCode(params);
};
const queryParams = reactive({
  factory: "",
  className: routerStore.subject,
  systemName: "",
  eqpId: "",
  type: "",
  pageNum: 1,
  pageSize: 20
});
// 递归解构
const fn = (arr, options = []) => {
  for (let i = 0; i < arr.length; i += 1) {
    if (Array.isArray(arr[i].children)) {
      if (arr[i].children.length > 0) {
        fn(arr[i].children, options);
      }
    } else {
      options.push(arr[i]);
    }
  }
  return options;
};
//查系统
const systemOptions = ref([]);
const getSystemOptions = async () => {
  const params = { factoryArea: queryParams.factory, className: queryParams.className };
  const res = await querySystemModelCondition(params);
  systemOptions.value = fn(res);
};
//查设备
const equipOptions = ref([]);
const treeChage = () => {
  getEquipOptions();
  getMaterialOptions();
};
const getEquipOptions = async () => {
  let systemCodes = [];
  if (queryParams.systemName) {
    systemCodes.push(queryParams.systemName);
  }
  const params = { className: queryParams.className, systemCode: queryParams.systemName };
  const res = await consumablelistInstalledDevices(params);
  console.log(res);
  equipOptions.value = res;
};
const remoteMethod = async query => {
  console.log(query);
  if (query) {
    let systemCodes = [];
    if (queryParams.systemName) {
      systemCodes.push(queryParams.systemName);
    }
    const params = { className: queryParams.className, systemCode: queryParams.systemName };
    const res = await consumablelistInstalledDevices(params);
    console.log(res);
    equipOptions.value = res;
  }
};
const materialOptions = ref([]);
//查耗材
const getMaterialOptions = async () => {
  // let systemCodes = [];
  // if (queryParams.systemName) {
  //   systemCodes.push(queryParams.systemName);
  // }

  // const res = await listInstalledFiltersMachine({});
  // materialOptions.value = res;
  let systemCodes = [];
  if (queryParams.systemName) {
    systemCodes.push(queryParams.systemName);
  }
  // const params = {
  //   category: "consumable",
  //   spareNameOrCode: "",
  //   typeCode: "",
  //   brandCode: "",
  //   modelCode: "",
  //   stockAlarm: false,
  //   supplyModel: "",
  //   className: queryParams.className,
  //   pageNum: 1,
  //   pageSize: 999
  // };
  // const res = await queryListPagesparePartNew(params);
  // materialOptions.value = res.data;

  const res = await listInstalledFiltersMachine({});
  materialOptions.value = res;
};
function getFilterTypes(filters: Record<string, any>) {
  return Object.keys(filters);
}
function getFilterItemLen(filterItem: any[]) {
  let len = 0;
  for (let i = 0; i < filterItem.length; i++) {
    len += filterItem[i].detailMap.length;
  }
  return len;
}
function getSingleItem(filters: Record<string, any>, key: string) {
  const list = Object.values(filters)[0];
  return list[0][key];
}
const tableData = ref([]);
// const total = ref(-1);
const tableLoading = ref(false);
const devTypeObj = {
  GAS: ["Unit"],
  WATER: ["RO", "SF", "UV", "TOC-UV", "UF", "CARBON", "RESIN", "MDG", "FP"],
  MACHINE: ["MAU", "NMAU", "AHU", "PCW"]
};
const handleQuery = async () => {
  //后台没有状态数据，传参去掉
  try {
    tableLoading.value = true;
    const devId = [];
    if (queryParams.eqpId) {
      devId.push(queryParams.eqpId);
    }
    const devType = devTypeObj[routerStore.subject];
    console.log(devType, "devType", routerStore.subject);
    const params = {
      devId,
      type: queryParams.type,
      devTypes: devType,
      className: queryParams.className,
      systemCode: queryParams.systemName,
      pageNum: queryParams.pageNum,
      pageSize: queryParams.pageSize,
      installStart: dateRange.value[0],
      installEnd: dateRange.value[1]
    };
    const res = await getListHistoryGrouping(params);
    total.value = res.total;
    tableData.value = res.data;
    tableLoading.value = false;
  } catch (error) {
    tableLoading.value = false;
  }
};
const formRef = ref(null);
const resetQuery = () => {
  formRef.value.resetFields();
  queryParams.factory = "";
  queryParams.className = routerStore.subject;
  queryParams.systemName = "";
  queryParams.eqpId = "";
  queryParams.type = "";
  dateRange.value = [];
  equipOptions.value = [];
  handleQuery();
};
onMounted(async () => {
  handleSystemFocus();
  if (route.query) {
    queryParams.eqpId = route.query.ffuCode;
    queryParams.type = route.query.filterType;
    // if (route.query.className) {
    //   queryParams.className = route.query.className;
    // }
  }
  getFactoryOption();
  getDepOption();
  getSystemOptions();
  getEquipOptions();
  getMaterialOptions();
  handleQuery();
  await useUpdateDomHeight(scrollbarHeight, objectModelTableRef, gap, defaultHeight);
});

onUnmounted(() => useCancelUpdateDomHeight());

const headerCellStyleFn = () => {
  const style = {};
  style["background-color"] = "var(--px-color-primary-light-9) !important";
  return style;
};

function goPms(data: any) {
  if (!data) {
    PxMessage.warning("未查询到历史工单，请查看历史线下工单表单");
    return;
  }
  const facCode = localStorage.getItem("facCode");
  const accessToken = getToken().accessToken || "";
  router.push({
    path: "/all/equip/epm/task/list",
    query: {
      fullpath: `/pmJob/list?jobId=${data}&jobStatus=COMPLETED&pmType=UNS&status=已完成&ssoToken=${accessToken}&facCode=${facCode}&isHiddenMenu=true`
    }
  });
}
</script>

<style lang="scss" scoped>
@import url("@/views/gas/consumption/scss/common.scss");

.filter-life-cycle {
  width: 100%;
  background-color: #fff;

  &-search {
    width: 100%;
  }

  .setContent-content-table {
    margin-top: 16px;
  }

  :deep(.px-form-item) {
    // width: 100%;
  }

  .flexNowrap {
    display: flex;
    flex-wrap: nowrap;
    align-items: center;
  }
}

.filter_bro ~ .filter_bro {
  border-top: 1px solid #e6e6e6;
}
</style>
